﻿using System;
using System.Linq;
using System.Web.Security;

namespace BetBattles.Authentification
{
    public class BetBattlesMembershipProvider: MembershipProvider
    {
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            // todo: validate data (user exist, wrong formats, etc)

            var entities = new BetBattlesEntities();

            if (entities.Users.Any(u=>u.Login == username))
            {
                status = MembershipCreateStatus.DuplicateUserName;
                return null;
            }

            if (RequiresUniqueEmail && entities.Users.Any(u => u.E_Mail == email))
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            var sault = GetMD5Hash(new Random().Next().ToString()).Substring(0, 5);
            var user = new User
                           {
                               Login = username,
                               E_Mail = email,
                               RegistrationDate = DateTime.Now,
                               PasswordSault = sault,
                               PasswordHash = GetMD5Hash(password + sault)
                           };

            try
            {
                entities.AddToUsers(user);
                entities.SaveChanges();
                
                status = MembershipCreateStatus.Success;
                return CreateMembershipUser(user);
            }
            catch (Exception ex) // todo: log error
            {
                status = MembershipCreateStatus.ProviderError;
                return null;
            }
            finally
            {
                entities.Dispose();
            }
        }

        private MembershipUser CreateMembershipUser(User user)
        {
            var msuser = new MembershipUser(
                "BetBattlesMembershipProvider", 
                user.Login, 
                user.UserId, 
                user.E_Mail, 
                null, 
                null, 
                true, 
                false, 
                user.RegistrationDate, 
                DateTime.Now, 
                DateTime.Now, 
                DateTime.Now, 
                DateTime.Now);

            return msuser;
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new NotImplementedException();
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            using (var entities = new BetBattlesEntities())
            {
                var user = entities.Users.FirstOrDefault(u => u.Login == username);
                if (user != null)
                {
                    if (user.PasswordHash == GetMD5Hash(password + user.PasswordSault))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private string GetMD5Hash(string input)
        {
            var x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
            bs = x.ComputeHash(bs);
            var s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("X2"));
            }
            string password = s.ToString();
            return password;
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override bool EnablePasswordRetrieval
        {
            get { throw new NotImplementedException(); }
        }

        public override bool EnablePasswordReset
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new NotImplementedException(); }
        }

        public override string ApplicationName
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new NotImplementedException(); }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresUniqueEmail // todo: get from web.config
        {
            get { return true; }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredPasswordLength // todo: get from config
        {
            get { return 6; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }
    }
}